package com.guigu.service;

import com.guigu.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${email.code.expire-minutes}")
    private Long expireMinutes;

    @Value("${email.code.resend-wait-seconds}")
    private Long resendWaitSeconds;

    // 发送验证码邮件
    public void sendVerificationCode(String toEmail) {
        // 1. 频率控制
        String lastSendKey = redisUtil.buildKey("email:time",toEmail);
        String lastSendTime = redisUtil.get(lastSendKey);
        if (lastSendTime != null) {
            long elapsed = System.currentTimeMillis() - Long.parseLong(lastSendTime);
            if (elapsed < resendWaitSeconds * 1000L) {
                throw new RuntimeException("请求过于频繁，请" + (resendWaitSeconds - elapsed / 1000) + "秒后再试");
            }
        }

        // 2. 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        log.info("EmailService.sendVerificationCode:生成验证码:{}", code);
        // 3. 发送邮件
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject("您的验证码");
            helper.setText(buildEmailContent(code), true); // true表示支持HTML

            mailSender.send(message);
            log.info("验证码邮件已发送至: {}", toEmail);
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            throw new RuntimeException("邮件发送失败，请稍后重试");
        }

        // 4. 存储验证码到Redis
        String redisKey = redisUtil.buildKey("email:code",toEmail);
        log.info("存储验证码的redisKey:{}", redisKey);
        redisUtil.setNx(redisKey, code, expireMinutes, TimeUnit.MINUTES);

        // 5. 记录最后发送时间
        redisUtil.setNx(lastSendKey,
                String.valueOf(System.currentTimeMillis()),
                resendWaitSeconds, TimeUnit.SECONDS);
    }

    // 验证码校验
    public boolean verifyCode(String email, String inputCode) {
        String redisKey = redisUtil.buildKey("email:code",email);
        String correctCode = redisUtil.get(redisKey);
        return inputCode != null && inputCode.equals(correctCode);
    }

    private String buildEmailContent(String code) {
        return String.format(
                "<div style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;\">" +
                        "    <h2 style=\"color: #444;\">验证码通知</h2>" +
                        "    <p>您的验证码是：<strong style=\"color: #ff5722; font-size: 20px;\">%s</strong></p>" +
                        "    <p>有效期 %d 分钟，请勿泄露给他人。</p>" +
                        "    <hr style=\"border: none; border-top: 1px solid #eee;\">" +
                        "    <p style=\"color: #999;\">如非本人操作，请忽略此邮件。</p>" +
                        "</div>",
                code, expireMinutes
        );
    }
}